package com.itboye.jigongbao.app

import android.app.Activity
import android.app.Application
import android.content.Context
import android.os.Looper
import android.util.Log
import com.bumptech.glide.Glide
import com.itboye.jigongbao.bean.LoginInfo
import com.itboye.jigongbao.db.CityDBManager
import com.itboye.jigongbao.db.DBManager
import com.itboye.jigongbao.retrofit.api.RetrofitApi
import com.itboye.jigongbao.retrofit.cache.ACache
import com.itboye.jigongbao.retrofit.cache.CacheInterceptor.interceptor
import com.itboye.jigongbao.retrofit.util.BuilMapUtils.getVersionCode
import com.itboye.jigongbao.utils.Const
import com.itboye.jigongbao.utils.CrashHandler
import com.itboye.jigongbao.utils.XGlideLoader
import com.umeng.analytics.MobclickAgent
import com.umeng.message.IUmengRegisterCallback
import com.umeng.message.PushAgent
import com.yancy.gallerypick.config.GalleryConfig
import okhttp3.Cache
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.io.File
import java.lang.ref.WeakReference
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * Created by Administrator on 2017/11/28.
 */
class MyApplication : Application() {

    var activityList: MutableList<WeakReference<Activity>> = LinkedList()

    var mRetrofit: Retrofit? = null

    var mIApi: RetrofitApi? = null

    var mACache: ACache? = null

    var loginInfo: LoginInfo? = null

    var galleryConfig: GalleryConfig? = null
    var mPushAgent: PushAgent? = null

    var role: String? = null

    companion object {
        var instance: MyApplication? = null
        val items = listOf("apple", "banana", "kiwi", "apple", "banana", "kiwi", "apple", "apple", "banana", "kiwi", "apple", "banana", "kiwi", "apple", "apple", "banana", "kiwi", "apple", "banana", "kiwi", "apple") as List<String>
        var cityDBManager: CityDBManager? = null
//        var addressDbHelper: AddressDbHelper? = null
    }

    override fun onCreate() {
        super.onCreate()
        instance = MyApplication@ this

        initCatchExceptionUtil()
        initRole()
//        clearImageDiskCache(applicationContext)
        initACache()
        //初始化数据库
        initCacheDb()
        initAddressDb()
        //初始化网络框架
        initRetrofit()

        initUploadImageConfig()

        initUmeng()
    }

    private fun initCatchExceptionUtil() {
        val crashHandler = CrashHandler.getInstance()
        crashHandler.init(this)
    }


    private fun initAddressDb() {
        cityDBManager = CityDBManager(this)
        cityDBManager!!.openDateBase()
//        AddressDbHelper().initAddressDB()
//        addressDbHelper = AddressDbHelper.instance
    }

    private fun initRole() {

//        role
    }

    private fun initUmeng() {

        mPushAgent = PushAgent.getInstance(applicationContext)
//注册推送服务，每次调用register方法都会回调该接口
        mPushAgent!!.register(object : IUmengRegisterCallback {

            override fun onSuccess(deviceToken: String) {
                //注册成功会返回device token
                Log.v(Const.TAG_DEBUG, "onSuccess-->$deviceToken")
            }

            override fun onFailure(s: String, s1: String) {
                Log.v(Const.TAG_DEBUG, "onFailure-->s:$s S1:$s1")
            }
        })

        MobclickAgent.setCatchUncaughtExceptions(true)
    }

    /**
     * 清除图片磁盘缓存
     */
    fun clearImageDiskCache(context: Context) {
        try {
            if (Looper.myLooper() === Looper.getMainLooper()) {
                Thread(Runnable {
                    Glide.get(context).clearDiskCache()
                    // BusUtil.getBus().post(new GlideCacheClearSuccessEvent());
                }).start()
            } else {
                Glide.get(context).clearDiskCache()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    private fun initUploadImageConfig() {

        galleryConfig = GalleryConfig.Builder()
                .imageLoader(XGlideLoader())    // ImageLoader 加载框架（必填）
//                .iHandlerCallBack(iHandlerCallBack)     // 监听接口（必填）
                .provider("com.yancy.gallerypickdemo.fileprovider")   // provider(必填)
//                .pathList(path)                         // 记录已选的图片
                .multiSelect(false)                      // 是否多选   默认：false
                .multiSelect(false, 9)                   // 配置是否多选的同时 配置多选数量   默认：false ， 9
//                .maxSize(9)                             // 配置多选时 的多选数量。    默认：9
                .crop(false)                             // 快捷开启裁剪功能，仅当单选 或直接开启相机时有效
                .crop(false, 1f, 1f, 500, 500)             // 配置裁剪功能的参数，   默认裁剪比例 1:1
                .isShowCamera(true)                     // 是否现实相机按钮  默认：false
                .filePath("/Gallery/Pictures")          // 图片存放路径
                .build()
    }

    private fun initACache() {
        mACache = ACache.get(this)
    }

    private fun initCacheDb() {
        DBManager().init(applicationContext)
    }


    fun addActivity(activity: Activity) {
        activityList.add(WeakReference(activity))
    }


    fun removeAllActivity() {
        for (activity in activityList) {
            if (activity.get() != null) {
                activity.get()!!.finish()
            }

        }
    }


    private fun initRetrofit() {
        //cache url
        val httpCacheDirectory = File(cacheDir, "responses")
        val cacheSize = 10 * 1024 * 1024 // 10 MiB
        val cache = Cache(httpCacheDirectory, cacheSize.toLong())

        //        作者：wanbo_
        //        链接：http://www.jianshu.com/p/e3d32c016c32
        //        來源：简书
        //        著作权归作者所有。商业转载请联系作者获得授权，非商业转载请注明出处。
        var okHttpClient = okhttp3.OkHttpClient()
        val clientBuilder = okHttpClient.newBuilder()
                //添加通用请求信息
                .addNetworkInterceptor { chain ->
                    var request = chain.request()
                    val builder = request.url().newBuilder()
                            .addQueryParameter(Const.APP_TYPE_KEY, Const.APP_TYPE_VALUE)
                            .addQueryParameter(Const.CLIEENT_ID_KEY, Const.CLIEENT_ID_VALUE)
                            .addQueryParameter(Const.APP_VERSION, getVersionCode().toString())
                    //                        //存在可能取不到Token的情况，所以只在有信息的时候调用getToken，否则传空。
                    request = request.newBuilder().url(builder.build()).build()
                    chain.proceed(request)
                }
                .retryOnConnectionFailure(true)
        val logging = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message -> Log.v("request", "addInterceptor" + message) })
        logging.level = HttpLoggingInterceptor.Level.BODY
        clientBuilder.addNetworkInterceptor(logging)


        okHttpClient = clientBuilder.cache(cache)
                .addInterceptor(interceptor)
                .addNetworkInterceptor(interceptor)
                //                .addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR)
                //                .addInterceptor(REWRITE_RESPONSE_INTERCEPTOR_OFFLINE)
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build()
        mRetrofit = Retrofit.Builder()
                .baseUrl(Const.API_URL)
                .client(okHttpClient)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        mIApi = mRetrofit!!.create(RetrofitApi::class.java!!)
    }

}